/**
 * Copyright (C) 2017-2018 pinganfang, Inc. All Rights Reserved.
 */
package com.pingan.haofang.searchcloud.solr.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.util.Assert;

/**
 * @author huhailiang937
 * @date 2017年4月7日下午11:40:05
 * @since 1.0.0
 */
public class DateUtils {

    public static final int YEAR_RETURN = 0;

    public static final int MONTH_RETURN = 1;

    public static final int DAY_RETURN = 2;

    public static final int HOUR_RETURN = 3;

    public static final int MINUTE_RETURN = 4;

    public static final int SECOND_RETURN = 5;

    public static String formatDate(final Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getFormatDate(final Date date) {
        return formatDate(date, "yyyyMMdd");

    }

    public static String formatDate(final Date date, final String pattern) {
        Assert.notNull(date, "Date");
        Assert.notNull(pattern, "Pattern");
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(date);
    }

    public static int getBetweenDays(final Date beginDate, final Date endDate){
        Long dateBetween = getBetween(beginDate,endDate,DAY_RETURN);
        return dateBetween.intValue();
    }

    public static Long getBetween(final Date beginDate, final Date endDate, int returnPattern) {
        Assert.notNull(beginDate, "beginDate can not null");
        Assert.notNull(endDate, "endDate can not null");

        Calendar beginCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();
        beginCalendar.setTime(beginDate);
        endCalendar.setTime(endDate);
        endCalendar.setTime(endDate);
        switch (returnPattern) {
        case YEAR_RETURN:
            return DateUtils.getByField(beginCalendar, endCalendar, Calendar.YEAR);
        case MONTH_RETURN:
            return DateUtils.getByField(beginCalendar, endCalendar, Calendar.YEAR) * 12
                    + DateUtils.getByField(beginCalendar, endCalendar, Calendar.MONTH);
        case DAY_RETURN:
            return DateUtils.getTime(beginDate, endDate) / (24 * 60 * 60 * 1000);
        case HOUR_RETURN:
            return DateUtils.getTime(beginDate, endDate) / (60 * 60 * 1000);
        case MINUTE_RETURN:
            return DateUtils.getTime(beginDate, endDate) / (60 * 1000);
        case SECOND_RETURN:
            return DateUtils.getTime(beginDate, endDate) / 1000;
        default:
            return 0L;
        }
    }

    private static long getByField(Calendar beginCalendar, Calendar endCalendar, int calendarField) {
        return endCalendar.get(calendarField) - beginCalendar.get(calendarField);
    }

    private static long getTime(Date beginDate, Date endDate) {
        return endDate.getTime() - beginDate.getTime();
    }
}
